
#include "Camera.h"

Camera::Camera(glm::vec3 pos, float hAngle, float vAngle, float s, float mSpeed)
{
	init(pos, hAngle, vAngle, s, mSpeed);
}

void Camera::init(glm::vec3 pos, float hAngle, float vAngle, float s, float mSpeed)
{
	//Set init values
	position = pos;
	horizontalAngle = hAngle;
	verticalAngle = vAngle;
	speed = 1;
	mouseSpeed = mSpeed;
	rightButtonPressed = false;
}

void Camera::update()
{
	//Compute the time in order to scale the speed and mouse speed
	static double lastTime = glfwGetTime();
	double currentTime = glfwGetTime();
	deltaTime = (float)(currentTime - lastTime);
	lastTime = currentTime;

	//Get current window size
	glfwGetWindowSize(&windowWidth, &windowHeight);
	
	//Get cursor position
	glfwGetMousePos(&xCursorPos, &yCursorPos);
	
	if(glfwGetMouseButton(GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS)
	{
		if(!rightButtonPressed)
			glfwGetMousePos(&xOldCursorPos, &yOldCursorPos);

		rightButtonPressed = true;
		
		//Compute angles
		horizontalAngle += mouseSpeed * deltaTime * (float)(xOldCursorPos - xCursorPos);
		verticalAngle += mouseSpeed * deltaTime * (float)(yOldCursorPos - yCursorPos);
		
		glfwGetMousePos(&xOldCursorPos, &yOldCursorPos);
	}
	if(glfwGetMouseButton(GLFW_MOUSE_BUTTON_RIGHT) != GLFW_PRESS)
		rightButtonPressed = false;

	//Update coordinate system of the camera
	direction =  glm::vec3(cosf(verticalAngle)*sinf(horizontalAngle), sinf(verticalAngle), cosf(verticalAngle)*cosf(horizontalAngle)); //Spherical coordinates to cartesian coordinates
	glm::vec3 rightVec = glm::vec3(sinf(horizontalAngle - 3.14f*0.5f), 0.0, cosf(horizontalAngle - 3.14f*0.5f));
	up = glm::cross(rightVec, direction);

	if(glfwGetKey('W') == GLFW_PRESS)
	{
		position += direction * deltaTime * speed;
	}
	if(glfwGetKey('S') == GLFW_PRESS)
	{
		position -= direction * deltaTime * speed;
	}
	if(glfwGetKey('D') == GLFW_PRESS)
	{
		position += rightVec * deltaTime * speed;
	}
	if(glfwGetKey('A') == GLFW_PRESS)
	{
		position -= rightVec * deltaTime * speed;
	}
	if(glfwGetKey('X') == GLFW_PRESS)
	{
		position -= glm::vec3(0.0, 1.0, 0.0) * deltaTime * speed;
	}
	if(glfwGetKey(GLFW_KEY_SPACE) == GLFW_PRESS)
	{
		
		position += glm::vec3(0.0, 1.0, 0.0) * deltaTime * speed;
	}
}